#pragma once
#include <iostream>
#include <unistd.h>
using namespace std;
#include "Init.hpp"
extern Log lg;
Init init;
class task
{

public:
    task() {}
    task(int sockfd, const uint16_t &clientport, const std::string &clientip)
        : sockfd_(sockfd), clientport_(clientport), clientip_(clientip)
    {
    }
    void run()
    {
        char buff[4096];
        ssize_t n = read(sockfd_, buff, sizeof(buff));
        if (n > 0)
        {
            buff[n] = 0;
            std::cout << "client key:" << buff << std::endl;
            std::string echo_string = init.Translation(buff);
            // sleep(5);
            lg(Warning, "write fail,sockfd:%d", sockfd_);

            ssize_t n = write(sockfd_, echo_string.c_str(), echo_string.size());
            std::cout << n << std::endl;
            if (n < 0)
            {
                lg(Warning, "write error,errno:%d,error string:%s", errno, strerror(errno));
            }
        }
        else if (n == 0)
        {
            lg(Info, "%s:%d quit,server close sockfd:%d", clientip_.c_str(), clientport_, sockfd_);
        }
        else
        {
            lg(Warning, "read error,server close sockfd:%d", sockfd_);
        }
        close(sockfd_);
    }
    void operator()()
    {
        run();
    }

private:
    int sockfd_;
    uint16_t clientport_;
    std::string clientip_;
};